package com.findweb.init;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import com.google.common.cache.CacheBuilder;


@Configuration
@EnableCaching
public class SecureTomcatConfiguration {
	
	@Value("${keystore.port}")
	private int port  ;
	@Value("${keystore.alias}")
	private String alias  ;
	@Value("${keystore.password}")
	private String password  ;
	@Value("${keystore.file}")
	private String file  ;
	@Value("${keystore.flag}")
	private boolean flag  ;
	
	@Bean
	public EmbeddedServletContainerFactory servletContainer() throws FileNotFoundException {
		TomcatEmbeddedServletContainerFactory f =
                new TomcatEmbeddedServletContainerFactory();
        f.addAdditionalTomcatConnectors(createSslConnector());
        return f;
	}

	private Connector createSslConnector() throws FileNotFoundException {
		Connector connector = new Connector(Http11NioProtocol.class.getName());
		Http11NioProtocol protocol = (Http11NioProtocol)connector.getProtocolHandler();
		connector.setPort(port);
		connector.setSecure(true);
		connector.setScheme("https");
		protocol.setSSLEnabled(flag);
		protocol.setKeyAlias(alias);
		protocol.setKeystorePass(password);
		protocol.setKeystoreFile(ResourceUtils.getFile(file).getAbsolutePath());
		protocol.setSslProtocol("TLS");
		
		return connector;
	}
	
	
	@Bean
    public CacheManager cacheManager() {
		GuavaCacheManager cacheManager = new GuavaCacheManager("trades");
		cacheManager.setCacheBuilder(CacheBuilder.newBuilder()
				.expireAfterWrite(60 , TimeUnit.SECONDS)
				.maximumSize(1000));
        return cacheManager;
    }
	
	

}
